package org.ytor.core.sqlflow.dsl.dsqlfile.loader.support;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.ytor.core.sqlflow.dsl.dsqlfile.DsqlSegment;
import org.ytor.core.sqlflow.dsl.dsqlfile.loader.DSQLoader;

import java.io.*;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * created by yangtong on 2025/8/7 18:20:47
 * <br/>
 */
public class YamlDSQLoader implements DSQLoader {

    private final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

    @Override
    public List<DsqlSegment> load(InputStream inputStream) throws IOException {
        DsqlSegment[] segments = mapper.readValue(inputStream, DsqlSegment[].class);
        return segments != null ? Arrays.asList(segments) : Collections.emptyList();
    }

    @Override
    public List<DsqlSegment> load(File file) throws IOException {
        try (InputStream in = new FileInputStream(file)) {
            return load(in);
        }
    }

    @Override
    public List<DsqlSegment> load(Path path) throws IOException {
        return load(path.toFile());
    }

    @Override
    public List<DsqlSegment> load(String resourcePath) throws IOException {
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);
        if (in == null) {
            throw new FileNotFoundException("Classpath resource not found: " + resourcePath);
        }
        return load(in);
    }
}
